package com.server.llh.llhserverwork.activity.query;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseActivity;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.SerTransWapBean;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.TimeUtils;
import com.server.llh.llhserverwork.utils.ToastTool;
import com.server.llh.llhserverwork.view.widget.JudgeDate;
import com.server.llh.llhserverwork.view.widget.ScreenInfo;
import com.server.llh.llhserverwork.view.widget.WheelMain;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-06.
 */

public class QueryMyTaskAllActivity extends LlhBaseActivity {
    private static final String TAG="QueryMyTaskAll";
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.startTime)
    TextView startTime;
    @BindView(R.id.stopTime)
    TextView stopTime;
    @BindView(R.id.queryServer)
    TextView queryServer;
    @BindView(R.id.timeView)
    LinearLayout timeView;
    @BindView(R.id.health_lv)
    ListView healthLv;
    SwipeRefreshLayout swipeContainer;
    private HealthTaskAdapter adapter = null;
    private	 final String transStatusa="4,5";
    String userId, orgId, orgType, userNameStr, signStatus, serSignRecordId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        userNameStr = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_NAMW,
                getApplicationContext());
        serSignRecordId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.SINGN_ID,
                getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        orgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        signStatus= SharedPreferenceUtil.getUserInfo(Constants.UserInfo.SIGN_STATUS,getApplicationContext());
        swipeContainer= (SwipeRefreshLayout)this. findViewById(R.id.swipe_container);
        titleName.setText("我的任务");

        setTimeView(startTime);
        setTimeView(stopTime);
        final String startTimeStr = startTime.getText().toString();
        final String stopTimeStr = stopTime.getText().toString();
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    getServerTask(userId, transStatusa, startTimeStr,
                            stopTimeStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getServerTask(userId, transStatusa, startTimeStr,
                stopTimeStr);
    }
    private String customerId;
    List<SerTransWapBean> listData=new ArrayList<>();
public void getServerTask(String userId,String transStatusa,String startTimeStr,
                          String stopTimeStrS){
    try {
        JSONObject json = new JSONObject();
        json.put("waitersId", userId);
        json.put("transStatus", transStatusa);
        json.put("startDateStr", startTimeStr);
        json.put("endDateStr", stopTimeStrS);
        customerId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.SIGN_CUSTOMER_ID,
                getApplicationContext());
        if (!TextUtils.isEmpty(customerId) && !"".equals(customerId)) {
            json.put("customerId", customerId);
        }
        LRequest lRequest = new LRequest();
        lRequest.addParam("searchTaskForWaitersForApp", URLEncoder.encode(json.toString(),"UTF-8"));
        lRequest.setUri(ServerPort.SEARCH_TASK_JSON);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }
            @Override
            public void onNext(String responseBean, String code) {

                if (responseBean != null) {
                    listData.clear();
                    Log.d(TAG,"responseBean=="+responseBean);
                    listData = new Gson().fromJson(responseBean,
                            new TypeToken<List<SerTransWapBean>>() {
                            }.getType());
                    adapter = new  HealthTaskAdapter(
                            getApplicationContext(), listData);
                    healthLv.setAdapter(adapter);
                }
            }
        });
    } catch ( Exception e) {
        e.printStackTrace();
    }
}
    @OnClick({R.id.startTime,R.id.main_back, R.id.stopTime, R.id.queryServer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_back:
                onBackPressed();
                break;
            case R.id.startTime:
                showTime(startTime);
                break;
            case R.id.stopTime:
                showTime(stopTime);
                break;
            case R.id.queryServer:
                final String startTimeStr = startTime.getText().toString();
                final String stopTimeStr = stopTime.getText().toString();
                getServerTask(userId, transStatusa, startTimeStr,
                        stopTimeStr);
                break;
        }
    }

    private String monthStr, dayStr;

    public void setTimeView(final TextView view) {
        Calendar calendar = Calendar.getInstance();
        int monthInt = calendar.get(Calendar.MONTH) + 1;
        int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthInt < 10) {
            monthStr = String.valueOf("0" + monthInt);
        } else {
            monthStr = String.valueOf(monthInt);
        }
        if (dayInt < 10) {
            dayStr = String.valueOf("0" + dayInt);
        } else {
            dayStr = String.valueOf(dayInt);
        }
        view.setText(calendar.get(Calendar.YEAR) + "-" + (monthStr) + "-"
                + dayStr + "");
    }

    WheelMain wheelMain;
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public void showTime(final TextView view) {
        LayoutInflater inflater = LayoutInflater
                .from(QueryMyTaskAllActivity.this);
        final View timepickerview = inflater.inflate(R.layout.timepicker, null);
        ScreenInfo screenInfo = new ScreenInfo(QueryMyTaskAllActivity.this);
        wheelMain = new WheelMain(timepickerview);
        wheelMain.screenheight = screenInfo.getHeight();
        String time = view.getText().toString();
        Calendar calendar = Calendar.getInstance();
        if (JudgeDate.isDate(time, "yyyy-MM-dd")) {
            try {
                calendar.setTime(dateFormat.parse(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        wheelMain.initDateTimePicker(year, month, day);
        new AlertDialog.Builder(QueryMyTaskAllActivity.this).setTitle("选择时间")
                .setView(timepickerview)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String time =wheelMain.getTime();
                         view.setText(wheelMain.getTime());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();

    }


    public class HealthTaskAdapter extends BaseAdapter {

        List<SerTransWapBean> listData;

        public List<SerTransWapBean> getListData() {
            return listData;
        }

        public void setListData(List<SerTransWapBean> listData) {
            this.listData = listData;
        }

        private Context context;

        public HealthTaskAdapter(Context context, List<SerTransWapBean> listData) {
            this.listData = listData;
            this.context = context;
        }

        @Override
        public int getCount() {
            return listData == null ? 0 : listData.size();
        }

        @Override
        public Object getItem(int arg0) {
            return listData == null ? null : listData.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            ViewHolder holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.subscribe_item_view, null);
                holder.server_name = (TextView) convertView
                        .findViewById(R.id.client_name);
                holder.client_age = (TextView) convertView
                        .findViewById(R.id.client_age);
                holder.server_time = (TextView) convertView
                        .findViewById(R.id.server_time);
                holder.order_time = (TextView) convertView
                        .findViewById(R.id.order_time);
                holder.client_num = (TextView) convertView
                        .findViewById(R.id.client_num);
                holder.client_server = (TextView) convertView
                        .findViewById(R.id.client_server);
                holder.subscribe_server_order = (TextView) convertView
                        .findViewById(R.id.subscribe_server_order);
                holder.subscribe_Revoke = (TextView) convertView
                        .findViewById(R.id.subscribe_Revoke);
                holder.client_address = (TextView) convertView
                        .findViewById(R.id.client_address);
                holder.ll_value = (LinearLayout) convertView
                        .findViewById(R.id.ll_value);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final SerTransWapBean taskBean = listData.get(position);
            holder.subscribe_server_order.setVisibility(View.INVISIBLE);
            holder.ll_value.setVisibility(View.GONE);
            holder.subscribe_server_order
                    .setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if ("2".equals(SharedPreferenceUtil.getUserInfo(
                                    Constants.UserInfo.SIGN_STATUS, getApplicationContext()))) {
                                ToastTool.showText(getApplicationContext(),
                                        "请签到,谢谢");
                                return;
                            } else {
                                long serTransId = taskBean.getSerTransId();
                                try {
                                    uploadReSend(serTransId, "6",position);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
            holder.subscribe_Revoke.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    long serTransId = taskBean.getSerTransId();
                    try {
                        uploadReSend(serTransId, "9",position);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            holder.order_time.setText(TimeUtils.dateToString(taskBean
                    .getAddTime()));
            holder.server_name.setText(taskBean.getCustomerName());
            holder.client_age.setText("");
            holder.client_num.setText(taskBean.getCustomerPhone());
//			holder.client_address.setVisibility(View.GONE);
//			holder.client_address.setText("￥ " + taskBean.getPrice() + " 元");
//			holder.client_server.setText(taskBean.getServiceName());
            if (taskBean.getRemark()!=null) {
                holder.client_server.setText("描述:"+taskBean.getRemark());
            }else{
                holder.client_server	.setVisibility(View.GONE);
            }
            holder.client_address.setText("" + taskBean.getServiceName());
            String startTime=TimeUtils.dateToString(taskBean
                    .getSerStartTime());
            String endTimeStr=TimeUtils.dateToString(taskBean.getSerEndTime());
            holder.server_time.setText(startTime.substring(5, startTime.length()-3)
                    + "--"
                    +endTimeStr.substring(5,endTimeStr.length()-3) );
            return convertView;
        }

        class ViewHolder {
            TextView server_name,server_time,server_finish,order_time,client_server,client_age
            ,client_address,client_num ,subscribe_Revoke,client_server_time,subscribe_server_order ;
            ImageView llh_image;
            LinearLayout ll_value;
        }

    }

    private void uploadReSend(long serTransId,   String transStatus, final int position) {
        try {
        JSONObject json = new JSONObject();
        json.put("serTransId", serTransId);
        json.put("transStatus", transStatus);
        json.put("waitersId", userId);
        json.put("waitersName", userNameStr);
            if (!"".equals( SharedPreferenceUtil.getUserInfo(
                    Constants.UserInfo.SER_SIGNRECORD_ID, getApplicationContext()))){
                json.put("serSignRecordId", SharedPreferenceUtil.getUserInfo(
                        Constants.UserInfo.SER_SIGNRECORD_ID, getApplicationContext()));
            }

            LRequest lRequest = new LRequest();
            try {
                lRequest.addParam("updateAppointmentStatusForApp",URLEncoder.encode( json.toString(),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            lRequest.setUri(ServerPort.UPDATE_AUTOMA_TASK_JSON);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
                }
                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null) {
                        Log.d(TAG,"responseBean=="+responseBean+"code=="+code);
                        if ("200".equals(code)){
                            listData.remove(position);
                            adapter.notifyDataSetChanged();
                        }
//                        final String startTimeStr = startTime.getText().toString();
//                        final String stopTimeStr = stopTime.getText().toString();
//                        getServerTask(userId, transStatusa, startTimeStr,
//                                stopTimeStr);
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }
    @Override
    public void showProgress() {
        try{
            showProgress(QueryMyTaskAllActivity.this);
        }catch (Exception e){

        }
    }
    @Override
    public void hideProgress() {
        try{
        closeProgress();
        }catch (Exception e){

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.activity_health_task_all;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }

}
